<template>
  <div>
    <h1>{{ isEditMode ? '编辑广告计划' : '创建广告计划' }}</h1>
    <el-form :model="adPlan" ref="adPlanForm" label-width="100px">
      <el-form-item label="名称" prop="name" :rules="[{ required: true, message: '请输入广告计划名称', trigger: 'blur' }]">
        <el-input v-model="adPlan.name" placeholder="请输入广告计划名称" />
      </el-form-item>

      <el-form-item label="预算" prop="budget" :rules="[{ required: true, message: '请输入预算', trigger: 'blur' }]">
        <el-input v-model="adPlan.budget" type="number" placeholder="请输入预算" />
      </el-form-item>

      <el-form-item label="状态" prop="status" :rules="[{ required: true, message: '请选择广告计划状态', trigger: 'blur' }]">
        <el-select v-model="adPlan.status" placeholder="请选择广告计划状态">
          <el-option label="激活" value="active" />
          <el-option label="非激活" value="inactive" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">{{ isEditMode ? '保存' : '创建' }}</el-button>
        <el-button @click="cancel" type="default">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';

// 判断是否为编辑模式
const isEditMode = ref(false);

// 广告计划表单数据
const adPlan = ref({
  name: '',
  budget: '',
  status: 'active',
});

// 获取广告计划详情
const getAdPlan = async () => {
  const route = useRoute();
  try {
    const response = await axios.get(`/api/adplans/${route.params.id}/`);
    adPlan.value = response.data;
  } catch (error) {
    console.error('Error fetching ad plan:', error);
  }
};

// 提交表单
const submitForm = async () => {
  const router = useRouter();
  try {
    const route = useRoute();
    if (isEditMode.value) {
      await axios.put(`/api/adplans/${route.params.id}/`, adPlan.value);
    } else {
      await axios.post('/api/adplans/', adPlan.value);
    }
    router.push({ name: 'AdPlanList' });
  } catch (error) {
    console.error('Error saving ad plan:', error);
  }
};

// 取消编辑
const cancel = () => {
  const router = useRouter();
  router.push({ name: 'AdPlanList' });
};

// 页面加载时获取广告计划
onMounted(() => {
  const route = useRoute();
  if (route.params.id) {
    isEditMode.value = true;
    getAdPlan();
  }
});
</script>
